﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Web.UI.WebControls;
using InhollandAir.App_Code;

namespace InhollandAir
{
    public partial class CreateAccount : System.Web.UI.Page
    {
        private bool _noValidationError;

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void EmailExistence(object source, ServerValidateEventArgs args)
        {
            string email = args.Value;
            if (!string.IsNullOrEmpty(email))
            {
                var conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ReadUser"].ToString());

                if (conn.State == ConnectionState.Closed) conn.Open();
                try
                {
                    SqlCommand cmd = new SqlCommand("select * from account where email=@Email", conn);
                    cmd.Parameters.AddWithValue("@Email", email);
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.HasRows) //Email allready exists in the DB
                    {
                        args.IsValid = false;
                        _noValidationError = false;
                    }
                    else
                    {
                        _noValidationError = true;
                        args.IsValid = true;
                    }
                }
                catch (SqlException exception)
                {
                    Logging.WriteError(exception.Message);
                    lbl_Error.Text = "Database unavailable, please try again later.";
                }
                catch (Exception exception)
                {
                    Logging.WriteError(exception.Message);
                    lbl_Error.Text = "Failed to send password, please contact the admin.";
                }
                finally
                {
                    conn.Close();
                }
            }
        }

        protected void UsernameExistence(object source, ServerValidateEventArgs args)
        {
            string username = args.Value;
            if (!string.IsNullOrEmpty(username))
            {
                var conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ReadUser"].ToString());
                try
                {
                    if (conn.State == ConnectionState.Closed) conn.Open();

                    SqlCommand cmd = new SqlCommand("select * from account where username=@Username", conn);
                    cmd.Parameters.AddWithValue("@Username", username);
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.HasRows)//Username allready exists in the DB
                    {
                        args.IsValid = false;
                        _noValidationError = false;
                    }
                    else
                    {
                        _noValidationError = true;
                        args.IsValid = true;
                    }
                }
                catch (SqlException exception)
                {
                    Logging.WriteError(exception.Message);
                    lbl_Error.Text = "Database unavailable, please try again later.";
                }
                catch (Exception exception)
                {
                    Logging.WriteError(exception.Message);
                    lbl_Error.Text = "Failed to send password, please contact the admin.";
                }
                finally
                {
                    conn.Close();
                }
            }
        }


        protected void btn_SubmitAccount_Click(object sender, EventArgs e)
        {
            string firstname = txt_Firstname.Text;
            string lastname = txt_Lastname.Text;
            string username = txt_Username.Text;
            string email = txt_Email.Text;
            string password = txt_Password.Text;
            string address = txt_Address.Text;
            string zipcode = txt_Zipcode.Text;
            string city = txt_City.Text;
            string country = txt_Country.Text;
            string phonenr = txt_Phonenr.Text;
            string birthdate = txt_DateOfBirth.Text;

            Tools.WaitAFewSeconds(1);
            if (!_noValidationError) return;

            Page.Validate();
            if (!Page.IsValid)
            {
                lbl_Error.Text = "Something went wrong, please try again.";
                lbl_Error.Visible = true;
                return;
            }

            try
            {
                string salt = Tools.CreateSalt();
                string hashedPassword = Tools.EncodePassword(password, salt);


                DateTime dt = DateTime.Parse(birthdate);
                string converted = dt.ToString("yyyy-MM-dd");
                var user = new User(firstname, lastname, username, email, hashedPassword, address, zipcode, city,
                                    country, phonenr, converted);

                //save in db
                user.Save();

                user.InsertSalt(user.id, salt);
                
                Response.Redirect(Request.Cookies["PendingFlightSearch"] != null? "FlightReservations.aspx": "Login.aspx");
            }
            catch (Exception ex)
            {
                lbl_Error.Text += ex.Message;
            }

        }

    }
}